<?php session_start();    

/*

***************************************
*                                     *
* Copyright 2011 David Matthew Pugh   *
* Contact Info:thebravedave@gmail.com *
*                                     *
***************************************

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
 
//makes sure they have been to the last page and filled out the information there, or it sends them to the cart.php page   
if(!isset($_SESSION['payment_card_number']))
{
    header("location:cart.php");
}
    
require_once "./services/webservices.php";   
include_once('WidgetShoppingCart.php');  
require_once('Mail.php'); 
    
// Include the header file:

$page_title = 'Step 3: Confirmation';
include("./includes/header.php");
 ?>
<link href="./includes/tables.css" rel="stylesheet" type="text/css" />
<br /><br />
<script type="text/javascript">

var formSubmitted=false;  
function preventDoubleSubmit() 
{  
   if(formSubmitted) 
   {  
      return false;  
   }
   var submitHistoryButton = document.getElementById("submitfinal");  
   submitHistoryButton.disabled=true; 
   document.getElementById("finalizeform").submit();
  
     
}  

</script>

<?php

$shipping_first_name = $_SESSION['shipping_first_name'];
$shipping_last_name = $_SESSION['shipping_last_name'];
$shipping_full_name = $shipping_first_name . " " . $shipping_last_name;
$shipping_street_address = $_SESSION['shipping_street_address'];
$shipping_city = $_SESSION['shipping_city'];
$shipping_state = $_SESSION['shipping_state'];
$shipping_zip_code = $_SESSION['shipping_zip_code'];
$shipping_carrier_name = $_SESSION['carrier_name'];
$service_name = $_SESSION['service_name'];
$service_id = $_SESSION['service_id'];
$items_total = number_format($_SESSION['items_total'], 2, '.', '');
$shipping_total = number_format($_SESSION['shipping_total'], 2, '.', '');
$total = number_format($_SESSION['total_after_shipping'], 2, '.', '');; 
$shiptocountrycode =    "US";


$country = "US";
$payment_first_name = $_SESSION['payment_first_name'];
$payment_last_name = $_SESSION['payment_last_name'];
$payment_street_address = $_SESSION['payment_street_address'];
$payment_city = $_SESSION['payment_city'];
$payment_state = $_SESSION['payment_state'];
$payment_type = "SALE";
$payment_email = $_SESSION['payment_email'];
$payment_zip_code = $_SESSION['payment_zip_code'];
$payment_card_number = $_SESSION['payment_card_number'];

$payment_cvv = $_SESSION['cvv'];
$currencyID = "USD"; 

$payment_cc_type = $_SESSION['payment_cc_type'];
$payment_expiration_month = $_SESSION['payment_expiration_month'];    
$payment_expiration_year = $_SESSION['payment_expiration_year'];         
$payment_expiration_date = $payment_expiration_month + "/" + $payment_expiration_year;
$lastfourdigits =  substr($payment_card_number, -4);     
$masked_card_number = "************" . $lastfourdigits;
$payment_cvv_length = strlen($payment_cvv);
$payment_cvv_masked = "";
while($payment_cvv_length !=0)
{
    $payment_cvv_masked .= "#";
    $payment_cvv_length = $payment_cvv_length-1;
}


  
if(!isset($_POST['submit']))
{
    $cart = unserialize($_SESSION['cart']);

    $cartidentifier = $cart->identifier;
    $shippingidentifier = $_SESSION['shipping_identifier'];

    if($cartidentifier != $shippingidentifier)
    {
    
        header("location:cart.php");
    }
    
    ?>            
  
        
    <?php   
    $itemarray = array();
    $categoryarray = array();
    $quantityarray = array();
    $priceperitemarray = array();
    $subtotalarray = array();
    $cartnumber = 0;
    foreach ($cart->items as $id => $info) 
    {   
        $cart_sw_id = $info['sw_id'];        
        $cart_info = "<tr align='center'>";
        $category = $info['category'];
        $name = $info['name']; 
        $name = urldecode($name);
        $qty = $info['qty'];
        $price = number_format($info['price'], 2, '.', '');
        $subtotal = $qty * $price;
        $subtotal = number_format($subtotal, 2, '.', '');      
        if($cart_sw_id == "")
        {            
            $itemarray[$cartnumber] = $name;           
            $categoryarray[$cartnumber] = $category;            
            $quantityarray[$cartnumber] = $qty;            
            $priceperitemarray[$cartnumber] = "$$price";           
            $subtotalarray[$cartnumber] = "$$subtotal";
           
        }
        else
        {
            $xml_name = new SimpleXMLElement($name);
            $gen_name = $xml_name->gw_name;
            
            $xml_build = "";
            foreach($xml_name->Item as $eachitem1)
            {
                $desc_category = $eachitem1->category;
                $descriptor = $eachitem1->descriptor;    
                $xml_build .= $desc_category . ":" . $descriptor . " ";
            }
            $name = $gen_name . "<br />" . $xml_build;
            
            $itemarray[$cartnumber] = $name;                       
            $categoryarray[$cartnumber] = $category;                 
            $quantityarray[$cartnumber] = $qty;              
            $priceperitemarray[$cartnumber] = "$$price";          
            $subtotalarray[$cartnumber] = "$$subtotal";   
           
        }
        
        $cartnumber ++;            
    } 
echo '<h2><b>Items Being Purchased</b></h2>';    
echo '<div class="table">';
echo '<ul>'; 
echo '<li class="title">Item</li>';
$num = 0;
while($num != $cartnumber)
{
    if($num % 2 == 0)
    {
        echo "<li class='even'>$itemarray[$num]</li>";   
    }
    else
    {
        echo "<li class='odd'>$itemarray[$num]</li>";   
    }
    
    $num++;
}
echo '</ul>';

echo '<ul>'; 
echo '<li class="title">Category</li>';
$num = 0;
while($num != $cartnumber)
{
    if($num % 2 == 0)
    {
        echo "<li class='even'>$categoryarray[$num]</li>";   
    }
    else
    {
        echo "<li class='odd'>$categoryarray[$num]</li>";   
    }
    
    $num++;
}
echo '</ul>';  
echo '<ul>'; 
echo '<li class="title">Quantity</li>';
$num = 0;
while($num != $cartnumber)
{
    if($num % 2 == 0)
    {
        echo "<li class='even'>$quantityarray[$num]</li>";   
    }
    else
    {
        echo "<li class='odd'>$quantityarray[$num]</li>";   
    }
    
    $num++;
}
echo '</ul>';  
echo '<ul>'; 
echo '<li class="title">Price Per Item</li>';
$num = 0;
while($num != $cartnumber)
{
    if($num % 2 == 0)
    {
        echo "<li class='even'>$priceperitemarray[$num]</li>";   
    }
    else
    {
        echo "<li class='odd'>$priceperitemarray[$num]</li>";   
    }
    
    $num++;
}
echo '</ul>';  
echo '<ul>'; 
echo '<li class="title">Subtotal</li>';
$num = 0;
while($num != $cartnumber)
{
    if($num % 2 == 0)
    {
        echo "<li class='even'>$subtotalarray[$num]</li>";   
    }
    else
    {
        echo "<li class='odd'>$subtotalarray[$num]</li>";   
    }
    
    $num++;
}
echo '</ul>';  
echo '</div>';
           
    
 ?>   

   <br /><br /><br /><br /><br /><br />

    <div class="table">
    <ul>
    <li class="title">
    <b>Total For Items</b>
    </li>     
    <li class="even">     
    $<?php print $items_total;?>
    </li>
    </ul>
    </div>
    <br /><br /><br /><br />
   
    <table>
        <tr align="center"><a href="cart.php">Edit</a></tr>
    </table>    
    <br />
    <?php 
    print "
    <h2><b>Shipping Information</b></h2>
      <div class='table'>
      <ul>
            <li class='title'>
                <b>Recipient's Name</b>
            </li>
            <li class='even'>
                $shipping_first_name  $shipping_last_name 
            </li>
      </ul>
      <ul>
            <li class='title'>
                <b>Destination Address</b>
            </li>
            <li class='even'>
                $shipping_street_address
            </li>
      </ul>
      <ul>
            <li class='title'>
                <b>City</b>
            </li>
            <li class='even'>
                $shipping_city
            </li>
      </ul>
      <ul>
            <li class='title'>
                <b>State</b>
            </li>
            <li class='even'>
                $shipping_state
            </li>
      </ul>
      <ul>
            <li class='title'>
                <b>Zipcode</b>
            </li>
            <li class='even'>
                $shipping_zip_code
            </li>
      </ul>
      <ul>
            <li class='title'>
                <b>Shipping Service</b>
            </li>
             <li class='even'>
                $shipping_carrier_name:$service_name
            </li>
      </ul>
       <ul>
            <li class='title'>
                <b>Shipping Total</b>
            </li>
             <li class='even'>
                $ $shipping_total
            </li>
      </ul>
      </div>
      ";

    ?>
    <br /><br /><br /><br />       

    
    <a href="orderinformation.php">Edit</a>
    
    <br />
    <br />
    
    <h2><b>Total After Shipping</b></h2>        
    <div class="table">
        <ul>
            <li class="title">
                <b>Sum Total</b></th>
            </li>
            <li class="even">
                <b><?php echo "$" . $total ?></b>
            </li>
        </ul>
    </div>
        
    <br />   
    <br />
    <br />
    <br />
    <?php 

            
        print "<h2><b>Credit Card Information</b></h2>    
        <div class='table'>
            <ul>
                <li class='title'>
                    <b>Name</b>
                </li>
                <li class='even'>
                    $payment_first_name $payment_last_name
                </li>
            </ul>
            <ul>
                <li class='title'>
                    <b>Address</b>
                </li>
                <li class='even'>
                    $payment_street_address
                </li>
            </ul>
            <ul>
                <li class='title'>
                    <b>City</b>
                </li>
                <li class='even'>
                    $payment_city
                </li>
            </ul>
            <ul>
                <li class='title'>
                    <b>State</b>
                </li>
                <li class='even'>
                    $payment_state
                </li>
            </ul>
            <ul>
                <li class='title'>
                    <b>Zipcode</b>
                </li>
                <li class='even'>
                    $payment_zip_code
                </li>
            </ul>
            <ul>
                <li class='title'>
                    <b>Card Number</b>
                </li>
                <li class='even'>
                    $payment_card_number
                </li>
            </ul>
            <ul>
                <li class='title'>
                    <b>Cvv</b>
                </li>
                <li class='even'>
                    $payment_cvv_masked
                </li>
            </ul>
            <ul>
                <li class='title'>
                    <b>Expiration Date</b>
                </li>
                <li class='even'>
                   $payment_expiration_month/$payment_expiration_year
                </li>
            </ul>
        </div><br /><br /><br /><br />
            ";
        
        
 
?> 

            
            <a href="payment.php">Edit</a>
            

    <br />
    <br />      
    <br />
    
       
   
   
            <div class="center1">
                <div class="center2">
                    <form action="finalize.php" method="POST" id="finalizeform" onsubmit="submitfinal.disabled=true; return true;">
                        <input type="hidden" name="submit" />
                        <input type="submit" name="submitfinal" id="submitfinal" value="Submit Order">
                        
                    </form>   
               </div>
            </div>
                         <br /><br /><br />         
              
    <?php
  
}
else
{    
    $cart = unserialize($_SESSION['cart']);
    $cartidentifier = $cart->identifier;
    $shippingidentifier = $_SESSION['shipping_identifier'];

    if($cartidentifier == $shippingidentifier)
    {   
        //need to recalculate the total in the cart
        $items_total = 0.0;
        foreach ($cart->items as $id => $info) 
        {    
            $qty = $info['qty'];
            $price = number_format($info['price'], 2, '.', '');
            $subtotal = $qty * $price;
            $items_total = $items_total + $subtotal; 
        } 
        
                                               
        $API_IPaddress = $_SERVER['REMOTE_ADDR'];   
       
        $shiptoname = urlencode($shipping_full_name); 
        $shiptostreet = urlencode($shipping_street_address); 
        $shiptocity = urlencode($shipping_city); 
        $shiptostate = urlencode($shipping_state); 
        $shiptozip = urlencode($shipping_zip_code);
        $shiptotal = urlencode($shipping_total); 
        $shiptocountrycode = urlencode($shiptocountrycode); 
       

        // Set request-specific fields.
        $API_IPaddress_encoded = urlencode($API_IPaddress);  
        $paymentType = urlencode($payment_type);             
        $firstName = urlencode($payment_first_name);
        $lastName = urlencode($payment_last_name);
        $creditCardType = urlencode($payment_cc_type);
        $creditCardNumber = urlencode($payment_card_number);
        // Month must be padded with leading zero
        $padDateMonth = urlencode(str_pad($payment_expiration_month, 2, '0', STR_PAD_LEFT));

        $expDateYear = urlencode($payment_expiration_year);
        $cvv2Number = urlencode($payment_cvv);
        $address1 = urlencode($payment_street_address);
        $city = urlencode($payment_city);
        $state = urlencode($payment_state);
        $zip = urlencode($payment_zip_code);
        $country = urlencode($country);                
        $amount = urlencode($total);
        $currencyID = urlencode($currencyID); 
        $email = urlencode($payment_email);           

        
        
        // Add request-specific fields to the request string.
        $nvpStr = "&IPADDRESS=$API_IPaddress_encoded&COUNTRYCODE=$country&CURRENCYCODE=$currencyID&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
                    "&EXPDATE=$padDateMonth" . "$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
                    "&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&EMAIL=$email&SHIPTONAME=$shiptoname&SHIPTOSTREET=$shiptostreet&SHIPTOCITY=$shiptocity&SHIPTOSTATE=$shiptostate&SHIPTOZIP=$shiptozip&SHIPTOCOUNTRYCODE=$shiptocountrycode";

        // Execute the API operation; see the PPHttpPost function above.
        $paypalhttppost = new paypalhttppost();
        $httpParsedResponseAr = $paypalhttppost->DoCreditCardTransaction($nvpStr);
       
        
        
        //if paypal sent a success response then proceed with order finalization.
        if("Success" == $httpParsedResponseAr["ACK"]) 
        {  
            $API_IPaddress = (string)$API_IPaddress;
            //get new order id (paypal payment id) from paypal response, also corelation id (id for transaction), and ACK
            $order_id = $httpParsedResponseAr["TRANSACTIONID"];   
            $_SESSION['order_id'] = $order_id;
            $correlation_id = $httpParsedResponseAr["CORRELATIONID"];  
            $ack = $httpParsedResponseAr["ACK"]; 
         
            $companynamearray = file('./configurational/companyname.php');        
            $companynamestring = "";
            foreach($companynamearray as $key => $value)
            {
                if(strpos($value, "companyname") !== false)
                {
                    $companynamestring = $value;
                }
            } 
            $companynamearray = explode("=", $companynamestring);
            $companyname = trim($companynamearray[1]);   
            
           
            
                        $mailarray = file('./configurational/mailconfiguration.php');
            $mailserverstring = "";
            $portstring = "";
            $usernamestring = "";
            $passwordstring = "";
            foreach($mailarray as $key => $value)
            {
                if(strpos($value, "mailserver") !== false)
                {
                    $mailserverstring = $value;
                }
                if(strpos($value, "port") !== false)
                {
                   $portstring = $value; 
                }
                if(strpos($value, "username") !== false)
                {
                    $usernamestring = $value;
                }
                if(strpos($value, "password") !== false)
                {
                    $passwordstring = $value;
                }
            }
            $mailusernamearray = explode("=", $usernamestring);
            $username = trim($mailusernamearray[1]);
            $passwordarray = explode("=", $passwordstring);
            $password = trim($passwordarray[1]);
            $portarray = explode("=", $portstring);
            $port = trim($portarray[1]);
            $hostarray = explode("=", $mailserverstring);
            $host = trim($hostarray[1]); 
         
 
         
            
            $email_string = "Thank you for your purchase from " . $companyname .  ".\nIn this email You will find the items that you purchased, and your shipping and billing information. You will also recieve the order number. \nIf you have questions about your order, email " . $username . ".  Include the order number in the subject. \nYou should recieve an email with your package(s) tracking information when your item has shipped. \n\n\n";
                 
             //insert statement to shipping table. 
             $shipping_object = new shipping();
           
            
             $shipping_object->first_name = $shipping_first_name;
             $shipping_object->last_name = $shipping_last_name;
             $shipping_object->street_address = $shipping_street_address;
             $shipping_object->city = $shipping_city;
             $shipping_object->state = $shipping_state;
             $shipping_object->zip_code = $shipping_zip_code;
             $shipping_object->service = $service_name;
             $shipping_object->carrier_name = $shipping_carrier_name; 
             $shipping_object->shipping_total = $shipping_total;
             $shipping_order_object->ip_address = $API_IPaddress;           
             $result = $shipping_object->addshippinginformation();
         
             $xml = new SimpleXMLElement($result);
            
             if($xml->added == "")
             {   
                 $shippingstatus = "false";
             }
             else
             {
               
                $shippingstatus = "true";
             }
         
           
            $order_status = "incomplete";  
                      
            $payment_order_object = new payment(); 
            $payment_order_object->lastfourdigits = $lastfourdigits;
            $payment_order_object->amount = $amount;
            $payment_order_object->order_status = 'incomplete';
            $payment_order_object->payment_type = 'creditcard';
            $payment_order_object->ip_address = $API_IPaddress;
            $payment_order_object->order_id = $order_id; 
            $payment_order_object->correlation_id = $correlation_id;   
            $payment_order_object->first_name = $payment_first_name; 
            $payment_order_object->last_name = $payment_last_name;
            $payment_order_object->street_address = $payment_street_address; 
            $payment_order_object->city = $payment_city; 
            $payment_order_object->state = $payment_state; 
            $payment_order_object->zip_code = $payment_zip_code; 
            $payment_order_object->email = $payment_email; 
            $result = $payment_order_object->addgeneralpaymentinformation();
            $xml = new SimpleXMLElement($result);
            if($xml->item_id != 0)
            {
                $paymentstatus ="true";
            }
            else
            {
                $paymentstatus ="false"; 
            }
            $creditcardPaymentResponse = $payment_order_object->addcreditcardpaymentinformation();
            $creditcardPaymentXml = new SimpleXMLElement($creditcardPaymentResponse);
            if($xml->item_id != 0)
            {
                $paymentstatus ="true";
            }
            else
            {
                $paymentstatus ="false"; 
            }
            
            $note = "Order Submitted";
            $getrequest_history = new orders_history();  
            $getrequest_history->order_id = $order_id;
            $getrequest_history->order_status = $order_status;
            $getrequest_history->note = $note;
            $getresponse_history = $getrequest_history->addordershistoryevent();
            $xml = new SimpleXMLElement($getresponse_history);
            if(isset($xml->item_id) && $xml->item_id != "")
            {
                $orderhistorystatus = "true";
            }
            else
            {
                $orderhistorystatus = "false";
            }
            //write and populate strings with order information to be sent through email   
            $shipping_string = "\nShipping information: \n\n First Name:" . $shipping_first_name . "\n Last Name:" . $shipping_last_name . "\n Street Address:" . $shipping_street_address . "\n City:" . $shipping_city . "\n State:" . $shipping_state . "\n Zip Code:" . $shipping_zip_code . "\n Shipping Method:" . $shipping_carrier_name . ":" . $service_name . "\n Shipping Cost:$" . $shipping_total . "\n\n\n";   
            $email_string = $email_string . "\nOrder ID:" . $order_id . "\n\n" . $shipping_string;
            $payment_string = "Payment information: \n\n  First Name:" . $payment_first_name . "\n Last Name" . $payment_last_name . "\n Street Address:" . $payment_street_address . "\n City:" . $payment_city . "\n State:" . $payment_state . "\n Zip Code:" . $payment_zip_code . "\n Payment Card Type:" . $payment_cc_type . "\n Credit Card Number:" . $masked_card_number;              
            $email_string = $email_string . $payment_string;
            $cart_string = "";          
            $admin_cart_string = "";          
            //this foreach statement parses a string that contains all of the items in the order in xml format
            //also populates and writes the cart contents onto a string to be sent as a confirmation email
            $order_object = new orders();
            $itemization = "<xml>";   
            $tmpcartnum = 0; 
                  
            foreach ($cart->items as $id => $info) 
            {
                
                //must account for specialized items vs non specialized items 
                $current_id = "";
                $specific_name = "";
                        $gw_id = $info['gw_id'];
                        $sw_id = $info['sw_id'];
                        if($sw_id == "")
                        {
                            $name2 = $info['name']; 
                            $current_id = $gw_id;
                        }
                        else
                        {   
                            $current_id = $sw_id;
                            $name2 = $info['name'];
                            $name2 = urldecode($name2);                           
                            $cart_name = new SimpleXMLElement($name2);
                            $gen_name = $cart_name->gw_name;                         
                            $xml_build = "";
                            
                            $specific_name = $gen_name . ' [';
                            $xml_build .= "<gw_name>" . $gen_name . "</gw_name>";
                            foreach($cart_name->Item as $eachitem2)
                            {
                                $isd_id_cart = $eachitem2->isd_id;
                                $isc_id_cart = $eachitem2->isc_id;
                                $category = $eachitem2->category;
                                $descriptor = $eachitem2->descriptor;
                                $specific_name .= $category . ":" . $descriptor . " ";
                                $xml_build .= "<descriptor_item><isd_id>" . $isd_id_cart . "</isd_id>" . "<descriptor>" . $descriptor . "</descriptor>" . "<isc_id>" . $isc_id_cart . "</isc_id>" . "<category>" . $category . "</category></descriptor_item>";
                                $name2 = (string)$xml_build;                                                               
                            }
                            $specific_name .= "]";                                                     
                        }
                       
                        $qty = $info['qty'];
                        $price = $info['price'];
                        $cart_string = $cart_string . "\n\nItem:" . $specific_name . "\nQuantity:" . $qty . "\nPrice per Unit:$" . $price;
                        $admin_cart_string .= $admin_cart_string . "\n\n Item ID:" . $current_id . "\nItem:" . $specific_name . "\nQuantity:" . $qty . "\nPrice per Unit:" . $price;     
                        $itemization = $itemization . '<Item><order_id>' . $order_id . '</order_id><gw_id>' . $gw_id . '</gw_id><sw_id>' . $sw_id . '</sw_id><name>' . $name2. '</name><qty>' . $qty . '</qty><price>' . $price . '</price></Item>'; 
                        $tmpcartnum++;
                       
         
              }
              $cart_string = "\n\nItems Purchased:" . $cart_string;
              $admin_cart_string = "\n\nItems Purchased:" . $admin_cart_string;
              $itemization .="</xml>";   
              
            //this sends the xml string that we just created to webservices. Webservices processes the string and adds the data to the database.
            $order_object->itemization = $itemization;
            $order_object->order_id = $order_id;
            $order_object->ip_address = $API_IPaddress;           
            $result = $order_object->addorderinformation();
                                                                                                                                                         
            $xml = new SimpleXMLElement($result);
            $number_inserted = $xml->number_inserted;
            //if number inserted is not equal to the  number in cart than set orderstatus to false which will trigger an email to the admin with the order information for furthur inspection 
            if($number_inserted == $tmpcartnum)
            {
                $orderstatus ="true";
            }
            else
            {
                $orderstatus ="false"; 
            }
             echo "Order Complete. You will recieve an email soon with your order information. Thank you for shopping with " . $companyname . ".";                     
           
             
            //complete string to be sent as email for purchase confirmation purposes.
            $email_string = $email_string . $cart_string;                                
            $purchase_total = "\n\nTotal After Shipping:$" .  $total;
            $email_string = $email_string . $purchase_total;
            
            
            //add calculated boxes for shipping to database
            $boxesorganized = $_SESSION['boxesorganized'];                                    
            foreach($boxesorganized as $boxnumber => $boxarray)
            {
                $order_object->status = "not shipped";
                $boxitemReturn = $order_object->addorderbox();
                $boxitemXml = new SimpleXMLElement($boxitemReturn);
                $order_box_id = $boxitemXml->order_box_id;
                
                foreach($boxarray as $key => $current_item_id_weight_array)
                {
                    foreach($current_item_id_weight_array as $current_item_id => $current_item_weight)
                    {         
                        $order_object->order_box_id = $order_box_id;
                        $order_object->item_id = $current_item_id;
                        $order_object->addorderboxitem();
                    }
                }          
            }
            
            
            //send notification email to admin if any of the order details are not recorded in the database. the admin will get an email with the full order info
            $adminmsg = "ORDER ID:" . $order_id . "\n" . $payment_string . $shipping_string . $admin_cart_string . "\n" . "Grand Total:" . $purchase_total . "\n";     
            if($shippingstatus=="false" || $orderstatus=="false" || $paymentstatus=="false" || $orderhistorystatus=="false")
            {     
                $from = $username;
                $to = $username;
                $body = $adminmsg; 
                $subject = "ORDER FINALIZATION ERROR. PLEASE READ EMAIL, CHECK ORDER FROM ADMIN SIDE, AND CONFIRM/FIX MISSING ITEMS."; 
                $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
                $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
                $mail = $smtp->send($to, $headers, $body);
                
              
            }
            
            
            
            //this email is sent to the purchaser    
            $from = $username;
            $to = $payment_email;
            $body = $email_string; 
            $subject = $companyname . ": Your Recent Purchase Information";
            $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
            $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
            $mail = $smtp->send($to, $headers, $body);
           
           
            //email the person in charge of controlling incoming order information. 
            $from = $username;
            $to = $username;
            $body = $adminmsg; 
            $subject = "Incoming Order Needs Processing"; 
            $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
            $smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));

            $mail = $smtp->send($to, $headers, $body);

            session_unset();
        }
        else  //this else statement catches if paypal merchant exchanges reply from your payment query didnt succeed.  
        {   
        echo '<br /><br />';
       
        echo '<br /><br />';   
            $failure_msg = $httpParsedResponseAr['L_LONGMESSAGE0'];
            $failure_msg = urldecode($failure_msg);
            print "<b>Payment failed:</b>" . $failure_msg . ".<br />" ;
            print 'This may be due to errors in shipping or payment details. Please check these details and try again.';
?>
            <br />
            <br />
            <form action="finalize.php" method="post">
            <input type="submit" id="resubmit" name="resubmit" value="Recheck Your Information">
            </form>
<?php    
        } 
       
       
     }
     else
     {
            echo 'Your Payment wasnt submitted because your cart contents were updated while you were in the middle of the checkout procedure.<br />';
            echo 'Please go back to your cart and start the checkout procedure from the beginning.<br /><br />';
?>
            <form action="cart.php" method="post">
            <input type="submit" id="resubmit" name="resubmit" value="go to cart">
            </form>
            <br /><br /><br />

<?php
     }
} 
   
 
?>
        
        
        
        
        
        
        
        
        
  
  
  
  
  
  

